<template>
	<view class="content">
		<view class="forms">
			<u--form :model="params" :rules="rules"	ref="ruleForm"  errorType="toast">
				<view class="form_item" style="margin-top: 20rpx;">
					<view class="title">
						<image class="img" src="https://www.qxszsn.cn/gy/file/xha-szsn-platform/applet/gap.png" alt="" /> 
						基本信息
					</view>
					<u-form-item label="标题" prop="title" borderBottom required>
						<u--input v-model="params.title" border="none" input-align="right" :readonly="type=='detail'" placeholder="请输入标题"></u--input>
					</u-form-item>
					<u-form-item label="分类" prop="type" border-bottom required>
						<u--input v-model="params.type" border="none" input-align="right" :readonly="type=='detail'" placeholder="请输入分类"></u--input>
					</u-form-item>
					<u-form-item label="作者" prop="author" border-bottom required>
						<u--input v-model="params.author" border="none" input-align="right" :readonly="type=='detail'" placeholder="请输入作者"></u--input>
					</u-form-item>
					<u-form-item label="封面" required border-bottom labelPosition="top">
						<view style="padding-top: 20rpx;">
							<u-upload
								v-if="type!='detail'"
								:fileList="fileList1"
								@afterRead="afterRead"
								name="1"
								@delete="deletePic"
								:previewFullImage="true"
								:maxCount="1"
							>
							</u-upload>
							<view class="imgs" v-if="type=='detail'&&params.imgUrl">
								<image class="img" :src="params.imgUrl" @click="picPreview(params.imgUrl)"></image>
							</view>
						</view>
					</u-form-item>
				</view>
				<view class="form_item" style="margin-top: 30rpx;">
					<view class="title">
						<image class="img" src="https://www.qxszsn.cn/gy/file/xha-szsn-platform/applet/gap.png" alt="" /> 
						笔记内容
					</view>
					<u-form-item label="" prop="content" border-bottom>
						<u--textarea v-model="params.content" count height="200" :disabled="type=='detail'" placeholder="请输入内容" maxlength="300"></u--textarea>
					</u-form-item>
				</view>
			</u--form>
		</view>
		<view class="foot">
			<u-button v-if="type=='add'" throttleTime="1000" type="primary" shape="circle" color="#3585F7" text="保 存" @click="submit"></u-button>
			<u-button v-if="type=='edit'" throttleTime="1000" type="primary" shape="circle" color="#3585F7" text="保存编辑" @click="update"></u-button>
			<u-button v-if="type=='detail'" throttleTime="1000" type="primary" shape="circle" color="#3585F7" text="编 辑" @click="type='edit'"></u-button>
		</view>
	</view>
	
</template>

<script>
	import { navigateTo,formatTime, getStorageSync } from '@/static/utils';
	export default {
		data() {
			return {
				type:'add',
				params: {
					title: '',
					type: '',
					author:'',
					content:'',
					userId:getStorageSync('userInfo')._id
				},
				rules: {
					'title':{type: 'string',required: true,message: '请填写标题',trigger: ['blur', 'change']},
					'type':{type: 'string',required: true,message: '请填写类别',trigger: ['blur', 'change']},
					'author':{type: 'string',required: true,message: '请填写作者',trigger: ['blur', 'change']},
					'content':{type: 'string',required: true,message: '请填写内容',trigger: ['blur', 'change']},
				},
				fileList1:[],
				detailId:"",
			};
		},
		onLoad(option) {
			this.type = option.type
			if (this.type=='detail') {
				this.params._id = option.id
				this.getDetail(option.id)
			}
		},
		methods:{
		  submit(){
				console.log(this.fileList1);
				if (this.fileList1.length==0) {
					uni.$u.toast('请上传封面照片！')
					return
				}else{
					this.params.imgUrl = this.fileList1[0].url
				}
				this.params.pubTime = formatTime(new Date())
				console.log(this.params);
				this.$refs['ruleForm'].validate().then(() => {
					uni.request({
						url: https://fc-mp-fff067d4-0ad0-46f1-8940-3076faaf2173.next.bspapp.com/addNotice',
						data: this.params,
						success: (res) => {
							console.log(res);
							if (res.data.code == 200) {
							   uni.$u.toast(res.data.mesg)
							}
						}
					})
				}).catch(errors => {
				  // uni.$u.toast('校验失败')
				})
			},
			update(){
				console.log(this.fileList1);
				if (this.fileList1.length==0) {
					uni.$u.toast('请上传封面照片！')
					return
				}else{
					this.params.imgUrl = this.fileList1[0].url
				}
				this.params.pubTime = formatTime(new Date())
				console.log(this.params);
				this.$refs['ruleForm'].validate().then(() => {
					uni.request({
						url: https://fc-mp-fff067d4-0ad0-46f1-8940-3076faaf2173.next.bspapp.com/updateNotice',
						data: this.params,
						success: (res) => {
							console.log(res);
							if (res.data.code == 200) {
							   uni.$u.toast('更新成功！')
								 this.type = 'detail'
							}else{
								uni.$u.toast('更新失败！')
							}
						}
					})
				}).catch(errors => {
				  // uni.$u.toast('校验失败')
				})
			},
			getDetail(id){
				uni.request({
					url: https://fc-mp-fff067d4-0ad0-46f1-8940-3076faaf2173.next.bspapp.com/noticeDetail',
					data: {_id:id},
					success: (res) => {
						console.log(res);
						if (res.data.code == 200) {
							this.params = res.data.data
							this.fileList1 = [
								{
									status: 'success',
									message: '',
									url: this.params.imgUrl
								}
							]
						}else{
							uni.$u.toast(res.data.mesg)
						}
					}
				})
			},
			picPreview(url){
				uni.previewImage({
					urls:[url],
					current:0,
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
			  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			  let lists = [].concat(event.file);
			  let fileListLen = this[`fileList${event.name}`].length;
			  lists.map((item) => {
			    this[`fileList${event.name}`].push({
			      ...item,
			      status: "uploading",
			      message: "上传中",
			    });
			  });
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uniCloud.uploadFile({
						filePath:url,			//所上传文件的路径地址；
						cloudPath: Date.now() + '.jpg',  //保存在云端的文件名，这里以时间戳命名
						success: (res) => {
							console.log(res);
							setTimeout(() => {
								resolve(res.fileID)
							}, 1000)
						},
						fail(res){
							console.log(res)
						}
					})
				})
			},
		}
	}
</script>

<style lang="less" scoped>
.content{
	width: 100vw;
	height: 100vh;
	display: flex;
	background: #f8f8f8;
	flex-direction: column;
	/deep/ .u-form-item__body__right__content__slot{
	  flex-direction: row !important;
	}
	.forms{
		flex: 1;
		overflow-y: auto;
		padding: 0rpx 20rpx 30rpx 20rpx;
		box-sizing: border-box;
		.imgs{
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			.img{
				width: 160rpx;
				height: 160rpx;
				border-radius: 4rpx;
				margin: 0 8px 8px 0;
			}
		}
		.form_item{
			width: 100%;
			background: #fff;
			padding: 0 20rpx 0 30rpx;
			box-sizing: border-box;
		  border-radius: 16rpx;
			.title{
			  width: calc(100% - 20rpx);
			  display: flex;
			  color: #333;
			  font-weight: 700;
			  align-items: center;
			  padding: 20rpx 0;
			  box-sizing: border-box;
			  border-bottom: 1rpx solid #EEF0F3;
			  font-size: 33rpx;
			  .img{
			    width: 34rpx;
			    height: 34rpx;
			    margin-right: 10rpx;
			  }
			}
			/deep/ .u-line{
				border-color: #EEF0F3 !important;
			}
			/deep/ .u-textarea{
				margin-top: 20rpx;
				background: #F6F7FB !important;
				border: none !important;
			}
			.line_form_input{
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				/deep/ .u-input{
					width: 320rpx !important;
					background: #F7F8FB !important;
					border-radius: 4rpx !important;
					flex: none;
					text-indent: 10rpx;
					margin-top: 10rpx;
					padding: 6rpx 0 !important;
				}
			}
		}
	}
	.foot{
		width: 100%;
		height: 50px;
		background: #fff;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}
}
</style>
